<template>
  <div>
    <el-form class="input-form"
             label-position="right"
             label-width="120px"
             ref="editForm"
             :rules="propRules"
             :disabled="propReadonly || formReadOnly"
             :model="form"
    >
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="申请科室" prop="deptId">
            <el-select v-model="form.deptId" filterable disabled>
              <el-option value="">请选择</el-option>
              <el-option v-for="dict in propDictionaries['deptId']" :key="dict.id" :label="dict.name"
                         :value="dict.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="请领单号" prop="oprtApplyKey">
            <el-input v-model="form.oprtApplyKey" :readonly="true" placeholder="自动设置" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="请领日期" prop="oprtApplyDate">
            <el-date-picker v-model="form.oprtApplyDate" type="date" :format="dates.defaultDatePattern"
                            :picker-options="dates.pickerOptions.date" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="申请人" prop="oprtApplyUser">
            <el-input v-model="form.oprtApplyUser" disabled/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="申请库存地" prop="warehouseIdFrom">
            <el-input v-model="form.warehouseNameFrom" :disabled="true"/>
          </el-form-item>

        </el-col>
        <el-col :span="6">
          <el-form-item label="配送仓库" prop="warehouseIdTo">
            <el-input v-model="form.warehouseNameTo" :disabled="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="手术名称" prop="oprtId" :rules="[{ required: true, message: '手术不能为空'}]">
            <FortenDataviewDown
              ref="oprtName"
              propDownType="form"
              propFieldText="oprtName"
              propClickType="input"
              :propForm="form"
              :propUserParam="{viewKey: 'select_oprt_by_patient',useMsg: '数据来源：院方-->手术信息'}"
              @select-change="selectChangeOprt"
            ></FortenDataviewDown>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="手术日期" prop="oprtDate">
            <el-date-picker
              v-model="form.oprtDate"
              type="date"
              :format="dates.defaultDatePattern"
              :picker-options="dates.pickerOptions.date"
              :readonly="true"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="患者名称" prop="patientName">
            <el-input v-model="form.patientName" :readonly="true" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="患者年龄" prop="patientAge">
            <el-input v-model="form.patientAge" :readonly="true" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="床位号" prop="bedNo">
            <el-input v-model="form.bedNo" :readonly="true" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="住院编号" prop="patientNo">
            <el-input v-model="form.patientNo" :readonly="true" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="主治医生" prop="docNameSug">
            <el-input v-model="form.docNameSug" :readonly="true" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="申请医生" prop="docNameApply">
            <el-input v-model="form.docNameApply" :readonly="true" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-collapse v-model="activeNames">
        <!--基本信息-->
        <el-collapse-item title="科室备货申请明细" name="1">
          <el-row :gutter="20">
            <div style="height:500px;overflow:auto;">
              <data-view
                v-show="!formReadOnly"
                propViewKey="dept_oprt_apply_item"
                propViewForm="dept/oprtapply-item/detail.vue"
                :propInitData="form"
                ref="childDataView"
                :propPreQueryWrapper='cpChildViewQueryWrapper'
                :propHidePageSearch="true"
                :propHideQueryButton="true"
                :propParentPage="propParentPage"
                :propAutoFetchData="false"
                :propHideAllButton="form.flowStatus != null && form.flowStatus != 'start'"
                @after-load="afterLoad"
                @view-ready="syncMatr"
                @edit-input="editInput"
                @extra-button-click="extraButtonClick"
                @select-change="selectChange"
                :propFlowKey="propParent.propFlowKey"
              >
              </data-view>
            </div>
          </el-row>
        </el-collapse-item>
      </el-collapse>
    </el-form>

    <el-dialog
      title="模板选择"
      :visible.sync="templetDialogVisible"
      :append-to-body="true"
      v-dialogDrag1
      v-dialog-resize
      width="80%"
      height="70vh"
      center>
      <templet-select
        :propPackType="propPackType"
        :propDefaultInput="defaultInput"
        @confirm-check="confirmCheck">
      </templet-select>
    </el-dialog>
  </div>
</template>

<script>
import templetSelect from '@/components/base/popover/PackTempletSelect.vue'

export default {
  data() {
    return {
      form: {},
      viewData: {},
      saveByAddRow: false, //是否添加明细保存的
      selectWarehouseColumns: [
        {
          name: 'name',
          label: '仓库名称',
          width: 150,
          search: true
        },
        {
          name: 'address',
          label: '仓库地址',
          span: 200,
          search: true
        }
      ],
      selectMatrColumns: [
        { title: '供应商名称', field: 'supplierName', width: 200, search: true },
        { title: '品名', field: 'name', width: 200, search: true },
        { title: '品规', field: 'spec', width: 200, search: true },
        { title: '厂商名称', field: 'mfgName', search: true },
        { title: '单品单位', field: 'skuUnit', width: 80, search: false },
        { title: '单品单价', field: 'skuPrice', width: 80, search: false },
        { title: '库存数量', field: 'stockCount', width: 80 }
      ],
      formReadOnly: false, //是否只读
      templetDialogVisible: false,
      propPackType: ['oper_apply', 'oper_bag'],
      defaultInput: [//其他默认信息输入

      ],
      activeNames: ['1']
    }
  },
  methods: {
    handleChangeOprt(value) {
      if (!value) {
        return
      }
      let params = { id: value }
      this.$ajax.get('/base/oprt/getOprtById', { params }).then((resp) => {
        let data = resp.data
        this.$set(this.form, 'patientName', data.patientName)
        this.$set(this.form, 'oprtCode', data.code)
        this.$set(this.form, 'oprtName', data.name)
        this.$set(this.form, 'patientId', data.patientId)
        this.$set(this.form, 'patientAge', data.patientAge)
        this.$set(this.form, 'bedNo', data.bedNo)
        this.$set(this.form, 'patientNo', data.inpatientNo)
        this.$set(this.form, 'oprtDate', data.date)
        this.$set(this.form, 'docNameApply', data.doctorNameApply)
        this.$set(this.form, 'docNameSug', data.doctorNameSug)
      })
    },
    //行编辑普通input框的修改事件，比如修改耗材包的数量后自动更新基本单位的数量
    editInput({ row, column }) {
      if (column.property == 'packageQty') {
        this.$set(row, 'skuQty', row.packageRate * row.packageQty)
        this.$set(row, 'amount', this.utilNum.toFixed(row.skuPrice * row.skuQty))
      }
    },
    afterLoad() {
      this.syncMatrUnit()
    },
    //行编辑选择事件
    async selectChange({ row, column }) {
      if (column.property == 'matrName') {
        this.matrChangeEvent(row, column.selectRow)
      }
      if (column.property == 'packageUnit') {
        this.matrUnitChangeEvent(row, column.selectRow)
      }
    },
    async extraButtonClick({ button, data, index }) {
      let { key: buttonKey } = button
      if (!this.form.id) {
        await this.propParent.ocAsynSaveViewForm()
      }
      if (buttonKey === 'oper_apply') {
        this.templetDialogVisible = true
      }
    },
    //行编辑耗材选择事件，在行编辑选择框选择后触发，根据选择的项来更新当前row的信息
    async matrChangeEvent(row, matr) {
      if (!this.form.id && this.form.id == null) {
        this.saveByAddRow = true
        await this.propParent.ocAsynSaveViewForm()
      }
      if (!this.form.id) {
        this.utilMessage.warning('主单据校验失败，请先填好必填项')
        this.templetDialogVisible = false
        return
      }

      const { id, name, spec, skuPrice, certificateNo, skuUnit, mfgName, supplierId, supplierName } = matr
      this.$set(row, 'oprtApplyId', this.form.id)
      this.$set(row, 'matrId', id)
      this.$set(row, 'matrName', name)
      this.$set(row, 'matrSpec', spec)
      this.$set(row, 'certificateNo', certificateNo)
      this.$set(row, 'mfgName', mfgName)
      this.$set(row, 'supplierId', supplierId)
      this.$set(row, 'supplierName', supplierName)
      this.$set(row, 'status', 1)

      //包装信息
      this.$set(row, 'packageRate', matr.packageRateApply)
      this.$set(row, 'packageUnit', matr.packageUnitApply)
      if (!row.packageQty) this.$set(row, 'packageQty', 1)

      //单品信息
      this.$set(row, 'skuQty', matr.packageRateApply * row.packageQty)
      this.$set(row, 'skuPrice', matr.skuPrice)
      this.$set(row, 'skuUnit', matr.skuUnit)

      //合计
      this.$set(row, 'amount', this.utilNum.toFixed(row.skuPrice * row.skuQty))
      this.syncMatrUnit()
    },
    //耗材单位选择事件
    matrUnitChangeEvent(row, packageUnit) {
      packageUnit && this.$set(row, 'packageUnit', packageUnit.packageUnit)
      && this.$set(row, 'packageRate', packageUnit.packageRate)
      && this.$set(row, 'skuQty', this.utilNum.toFixed(packageUnit.packageRate * row.packageQty))
      && this.$set(row, 'amount', this.utilNum.toFixed(packageUnit.packagePrice * row.packageQty))
    },
    syncMatr() {
      let deptIdApply = this.form.deptId ?  this.form.deptId : this.utils.getCurrentUser().deptId
      let warehouseIdStock = this.form.warehouseId ?  this.form.warehouseId : this.utils.getCurrentWarehouse().applyWarehouseId

      let wrapper = this.$newWrapper()//.ge('canUseCount', 0)

      //wrapper条件
      this.$refs.childDataView.setEditQueries('matrName', wrapper)

      //固定数据筛选参数
      let userParam = {
        'deptIdApply': deptIdApply,
        'warehouseIdStock': warehouseIdStock,
        busType: 'deptApply',
        viewKey: 'base_matr_select',
        checkType: 'radio',
        useMsg: '数据筛选条件：科室范围内的正常流通的耗材，并且未添加到当前申请单中(若无可选耗材，请联系运营)',
        //下一个编辑单元格
        nextFieldEditName: 'packageUnit',
        //筛选耗材的sql语句
        sqlFilterMatr: " and matr.id not in ( select matr_id from dept_oprt_apply_item where oprt_apply_id = '" + this.form.id + "' ) "
      }
      this.$refs.childDataView.setEditUserParam('matrName', userParam)
    },
    //耗材单位初始化
    syncMatrUnit() {
      //wrapper条件
      let wrapper = this.$newWrapper()
        .eq('flagApply', true)
      this.$refs.childDataView.setEditQueries('packageUnit', wrapper)

      //固定数据筛选参数
      let userParam = {
        viewKey: 'select_matr_unit_purchase',
        checkType: 'radio',
        useMsg: '数据筛选条件：所选耗材的有效请领单位',

        //前一个编辑单元格字段名
        beforeFieldEditName: 'matrName',
        //前一个单元格编辑值为空的提示
        beforeNullMsg: '请先选择耗材',
        //查询单位时的条件字段
        beforeFieldQueryName: 'matrId',
        //下一个编辑单元格
        nextFieldEditName: 'packageQty'
      }
      this.$refs.childDataView.setEditUserParam('packageUnit', userParam)
    },
    fetchChildData() {
      this.$refs.childDataView.setQueryWrapper(this.getChildViewQueryWrapper(), false)
      this.$refs.childDataView.fetchData()
      // this.$refs.childDataView.fetchData()
      this.saveByAddRow = false
    },
    getChildViewQueryWrapper() {
      let queryWrapper = this.$newWrapper()
      if (this.form.id) {
        queryWrapper.eq('oprtApplyId', this.form.id).isNull('packId')
      } else {
        queryWrapper.ne('oprtApplyId', -1)
      }
      return queryWrapper
    },
    async confirmCheck(rows) { //包确认选择事件钩子
      if (!this.form.id && this.form.id == null) {
        this.saveByAddRow = true
        await this.propParent.ocAsynSaveViewForm()
      }
      if (!this.form.id) {
        this.utilMessage.warning('主单据校验失败，请先填好必填项')
        this.templetDialogVisible = false
        return
      }

      if (!rows.length) {
        return
      }
      let params = {
        oprtApplyId: this.form.id,
        packTemplets: rows
      }
      this.$ajax.post('/dept/oprt_apply_item/addByTemp', params).then(response => {
        response.success && this.utilMessage.success(response.msg)
        this.templetDialogVisible = false
        this.fetchChildData()
      })
    },
    //患者选择后
    selectChangeOprt({fieldText, row}) {
      this.$set(this.form, 'patientName', row.patientName)
      this.$set(this.form, 'oprtCode', row.code)
      this.$set(this.form, 'oprtName', row.name)
      this.$set(this.form, 'patientId', row.patientId)
      this.$set(this.form, 'patientAge', row.patientAge)
      this.$set(this.form, 'bedNo', row.bedNo)
      this.$set(this.form, 'patientNo', row.inpatientNo)
      this.$set(this.form, 'oprtDate', row.date)
      this.$set(this.form, 'docNameApply', row.doctorNameApply)
      this.$set(this.form, 'docNameSug', row.doctorNameSug)
      this.$set(this.form, 'oprtId', row.id)
    },
  },
  created() {
    this.$emit('event-register', {
      validate: (callback) => {
        this.$refs.editForm.validate(callback)
      },
      beforeSave: () => {
        this.$emit('data-callback', this.form)
        return true
      },
      afterMove: (formData, initData) => {
        this.form = global.utils.jsonClone(formData)
        this.form.oprtApplyType = 1//手术科室申请
        if (!this.form.id) {
          this.$set(this.form, 'oprtApplyDate', new Date().format(this.dates.defaultDatePattern))

          //申请科室及用户信息
          let CurrentUser = this.utils.getCurrentUser()
          if (CurrentUser) {
            this.$set(this.form, 'deptName', CurrentUser.deptName)
            this.$set(this.form, 'deptId', CurrentUser.deptId)
            this.$set(this.form, 'oprtApplyUser', CurrentUser.name)
          }

          //申请及请领库存地
          let currentWarehouse = this.utils.getCurrentWarehouse()
          if (currentWarehouse && currentWarehouse.applyWarehouseId) {
            this.$set(this.form, 'warehouseIdFrom', currentWarehouse.id)
            this.$set(this.form, 'warehouseNameFrom', currentWarehouse.warehouseName)

            this.$set(this.form, 'warehouseNameTo', currentWarehouse.applyWarehouseName)
            this.$set(this.form, 'warehouseIdTo', currentWarehouse.applyWarehouseId)
          }

          let warehouseIdStock = this.form.warehouseId ?  this.form.warehouseId : this.utils.getCurrentWarehouse().applyWarehouseId
          if (!warehouseIdStock) {
            global.utilMessage.alertFail('未找到目标请领仓库，请到工作台检查是否已选择当前仓库或者当前仓库是否有可用的请领仓库!', '系统提示', {
              confirmButtonText: '确定',
              type: 'warning',
              callback: action => {
                this.propParent.setViewFormVisible(false)
              }
            })

            return false
          }
          this.$refs.oprtId.focus()
        } else {
          this.$refs.childDataView.setQueryWrapper(this.getChildViewQueryWrapper(), !this.saveByAddRow)
        }
        this.$refs.childDataView.setEditColumns('matrName', this.selectMatrColumns)
        this.syncMatr()
      },
      afterSave: () => {
        let deptName = this.propDictionaries.deptId.filter(dept => this.form.deptId == dept.id).map(dept => dept.name)[0]
      },
      beforeDelete: () => {
        return true
      },
      afterDelete: () => {
      },
      beforeFlow: (flowButtonKey) => {
        return true
      },
      afterFlow: (flowButtonKey) => {
      },
      beforeClose: () => {
        return true
      }
    })
  },
  props: {
    propParent: Object,
    propInitData: Object,
    propPrimaryKey: String,
    propDictionaries: Object,
    propCurrentRow: Object,
    propViewFormData: Object,
    propReadonly: Boolean,
    propStatus: String,
    propRules: Object,
    propParentPage: Object
  },
  components: {
    templetSelect
  },
  computed: {
    cpChildViewQueryWrapper() {
      let queryWrapper = this.$newWrapper()
      if (this.form.id) {
        queryWrapper.eq('oprtApplyId', this.form.id)
      } else {
        queryWrapper.ne(1, 1)
      }
      return queryWrapper
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
}
</style>
